import { querySql } from '../db/mysql';
import { validationResult } from 'express-validator';
import boom from '@hapi/boom';
import md5 from '../utils/md5';
import { CODE_ERROR, CODE_SUCCESS } from '../utils/constant';
import {JWTsign} from '../utils/user-jwt'
// 登录
export function login(req, res, next) {
    // 入参校验
    const err:any = validationResult(req);

    if(!err.isEmpty()){
        const [{msg}] = err.errors;

        console.log('err', boom.badRequest(msg))
        
        next(boom.badRequest(msg))
    } else {
        let { username, password }: {username: string, password: string} = req.body
        
        // 加密密码
        // password= passMd5(password)

        const queryStr = `select * from user where account='${username}' and password= '${password}'`;

        querySql(queryStr).then((user:any) => {
            console.log('用户信息', user)
            if(!user || user.length === 0) {
                res.json({
                    code: CODE_ERROR,
                    msg: '用户名或密码错误',
                    data: null
                })
            } else {
                const {name, role, account, gitlabToken, identification} = user[0]
                
                // 参数1：包含的用户数据 2：私钥 3:过期时间
                // 生成token
                const token= JWTsign({username})
                res.json({
                    code: CODE_SUCCESS,
                    msg: '登录成功',
                    data: {
                        token,
                        userData: {name, role, account, gitlabToken, identification}
                    }
                })
            }
        })
    }
}
